package com.riaplatform.sample10;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.util.Log;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XmlParser extends Activity {
	private TextView tv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv	=	new TextView(this);
        try
        {
        	URL	url		=	new URL("http://10.13.36.90:8080/test1/testlist.xml");
        
        	
        	SAXParserFactory parserModel	=	SAXParserFactory.newInstance();
        	SAXParser concreteParser			= parserModel.newSAXParser();
        	
        	XMLReader myReader				=	concreteParser.getXMLReader();
        	MySampleHandler mySample		=	new MySampleHandler(this);
        	myReader.setContentHandler(mySample);
        	
        	myReader.parse(new InputSource(url.openStream()));
        	
        	Log.i("TRACE", "Success");
        }catch(Exception e)
        {
        	tv.setText("Error: "+e.getMessage());
        }
        setContentView(tv);
    }
    public void updateTextView(String text)
    {
    	tv.setText(text);
    	
    }
}
class MySampleHandler extends DefaultHandler
{
	private StringBuffer names	=	new StringBuffer();
	private StringBuffer comps = new StringBuffer();
	private StringBuffer departs = new StringBuffer();
	
	private boolean hasName = false;
	private boolean hasCompany = false;
	private boolean hasDepart = false;
	private XmlParser xp;
	
	public MySampleHandler(XmlParser xp)
	{
		this.xp		=		xp;
	}
	public void startElement(String uri, String localName, String qName, Attributes atts)
	{
		if(localName.equals("name"))
		{
			hasName = true;
		}
		else if(localName.equals("company"))
		{
			hasCompany = true;
		}
		else if(localName.equals("department"))
		{
			hasDepart = true;
		}
	}
	public void endElement(String uri, String localName, String qName)
	{
		if(localName.equals("person"))
		{
			xp.updateTextView(names.toString()+"\n"+comps.toString()+"\n"+departs.toString());
		}
	}
	public void characters(char[] chars, int start, int leng)
	{
		if(hasName)
		{
			hasName = false;
			names.append(chars, start, leng);
		}
		else if(hasCompany)
		{
			hasCompany = false;
			comps.append(chars, start, leng);
		}
		else if(hasDepart)
		{
			hasDepart = false;
			departs.append(chars, start, leng);
		}
	}
	
}